import os
import subprocess

import mimetypes

from damn.transcoder import TranscoderFailedException, BaseTranscoder

from damn.util import ExecutableDependencies

ExecutableDependencies(['sox'])

class SoundTranscoder(BaseTranscoder):
  transcoder = True
  convert_map = {"video/mp4" : ["audio/ogg"], 
                  "audio/ogg" : ["audio/ogg"],
                  "audio/mpeg" : ["audio/ogg"]}
  _options = [('quality', float, None),]
  options_map = {"video/mp4" : _options,
                 "audio/ogg" : _options, 
                 "audio/mpeg" : _options}

  def transcode(self, anAssetReference, dstFormat, **kwargs):  
    filePath = super(SoundTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
    
    anURI = anAssetReference.file.fileName  
    try:
      try:
        p = subprocess.Popen(['sox', '--no-glob', anURI, '--norm', '--add-comment', '"Transcoder=Transcoded by D.A.M.N."', filePath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        s, t = p.communicate()
        if p.returncode != 0:
          raise TranscoderFailedException('SoundTranscoder failed! (return code %d) %s %s'%(p.returncode, s, t))
      except OSError:
        raise TranscoderFailedException('SoundTranscoder failed! %s %s'%(s, t))
    except TranscoderFailedException as e:
      if os.path.exists(filePath): os.remove(filePath)
      raise e
      
    return filePath
